package com.zxcz.redis;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;


/**
 * redis缓存配置类
 * @author root
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheConfiguration {
	@Resource
    private RedissonConnectionFactory factory;
	
	@Bean
	public RedisTemplate<String, Object> redisTemplate() {
		// 解决fastjson反序列化失败
		ParserConfig.getGlobalInstance().addAccept("com.zxcz.domain.");
		ParserConfig.getGlobalInstance().addAccept("javax.crypto.");
		
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);
		
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		MyFastJsonRedisSerializer<Object> fastJsonRedisSerializer = new MyFastJsonRedisSerializer<>(Object.class);
		
        // key采用string的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key采用fastjson的序列化方式
        template.setHashKeySerializer(fastJsonRedisSerializer);
		
		//设置value采用fastjson序列化方式
		template.setValueSerializer(fastJsonRedisSerializer);
		template.setHashValueSerializer(fastJsonRedisSerializer);
		
		template.afterPropertiesSet();
		return template;
	}
}
